use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime};
use std::fmt;
use uuid::Uuid;
use rust_decimal::Decimal;
use rust_decimal::prelude::{FromPrimitive, ToPrimitive};

use crate::error::{Result, VerticaError};

/// Vertica data type constants (OID values)
pub mod vertica_types {
    /// BOOLEAN type
    pub const BOOLEAN: u32 = 5;
    /// INTEGER type
    pub const INTEGER: u32 = 6;
    /// FLOAT type
    pub const FLOAT: u32 = 7;
    /// CHAR type
    pub const CHAR: u32 = 8;
    /// VARCHAR type
    pub const VARCHAR: u32 = 9;
    /// DATE type
    pub const DATE: u32 = 10;
    /// TIME type
    pub const TIME: u32 = 11;
    /// TIMESTAMP type
    pub const TIMESTAMP: u32 = 12;
    /// TIMESTAMPTZ type
    pub const TIMESTAMPTZ: u32 = 13;
    /// INTERVAL type
    pub const INTERVAL: u32 = 14;
    /// TIMETZ type
    pub const TIMETZ: u32 = 15;
    /// NUMERIC type
    pub const NUMERIC: u32 = 16;
    /// VARBINARY type
    pub const VARBINARY: u32 = 17;
    /// UUID type
    pub const UUID: u32 = 2950;
    /// BIGINT type
    pub const BIGINT: u32 = 20;
    /// LONG VARCHAR type
    pub const LONG_VARCHAR: u32 = 115;
    /// LONG VARBINARY type
    pub const LONG_VARBINARY: u32 = 116;
    /// BINARY type
    pub const BINARY: u32 = 117;
    /// INTERVAL YEAR TO MONTH type
    pub const INTERVAL_YM: u32 = 114;
    /// TEXT type (alias for LONG VARCHAR)
    pub const TEXT: u32 = 115;
    /// NULL type
    pub const NULL: u32 = 0;
}

/// Database value types
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// 表示空值
    Null,
    /// 表示布尔值类型，包含一个 bool 类型的值
    Boolean(bool),
    /// 表示 32 位有符号整数类型，包含一个 i32 类型的值
    Int(i32),
    /// 表示 64 位有符号整数类型，包含一个 i64 类型的值
    BigInt(i64),
    /// 表示 32 位浮点数类型，包含一个 f32 类型的值
    Float(f32),
    /// 表示 64 位浮点数类型，包含一个 f64 类型的值
    Double(f64),
    /// 表示字符串类型，包含一个 String 类型的值
    String(String),
    /// 表示二进制数据类型，包含一个 Vec<u8> 类型的值
    Binary(Vec<u8>),
    /// 表示日期类型，包含一个 NaiveDate 类型的值
    Date(NaiveDate),
    /// 表示时间类型，包含一个 NaiveTime 类型的值
    Time(NaiveTime),
    /// 表示时间戳类型，包含一个 NaiveDateTime 类型的值
    Timestamp(NaiveDateTime),
    /// 表示通用唯一标识符类型，包含一个 Uuid 类型的值
    Uuid(Uuid),
    /// 表示十进制数值类型，包含精度和小数位信息
    Decimal(Decimal),
}

impl Value {
    /// 尝试将值转换为 bool 类型
    pub fn as_bool(&self) -> Result<bool> {
        if let Value::Boolean(b) = self {
            Ok(*b)
        } else {
            Err(VerticaError::TypeConversion("Value is not a boolean".to_string()))
        }
    }

    /// 尝试将值转换为 i32 类型
    pub fn as_i32(&self) -> Result<i32> {
        if let Value::Int(i) = self {
            Ok(*i)
        } else {
            Err(VerticaError::TypeConversion("Value is not an int".to_string()))
        }
    }

    /// 尝试将值转换为 i64 类型
    pub fn as_i64(&self) -> Result<i64> {
        if let Value::BigInt(i) = self {
            Ok(*i)
        } else {
            Err(VerticaError::TypeConversion("Value is not a bigint".to_string()))
        }
    }

    /// 尝试将值转换为 f32 类型
    pub fn as_f32(&self) -> Result<f32> {
        if let Value::Float(f) = self {
            Ok(*f)
        } else {
            Err(VerticaError::TypeConversion("Value is not a float".to_string()))
        }
    }

    /// 尝试将值转换为 f64 类型
    pub fn as_f64(&self) -> Result<f64> {
        if let Value::Double(f) = self {
            Ok(*f)
        } else {
            Err(VerticaError::TypeConversion("Value is not a double".to_string()))
        }
    }

    /// 尝试将值转换为 String 类型
    pub fn as_string(&self) -> Result<String> {
        if let Value::String(s) = self {
            Ok(s.clone())
        } else {
            Err(VerticaError::TypeConversion("Value is not a string".to_string()))
        }
    }

    /// 尝试将值转换为 Vec<u8> 类型
    pub fn as_bytes(&self) -> Result<Vec<u8>> {
        if let Value::Binary(b) = self {
            Ok(b.clone())
        } else {
            Err(VerticaError::TypeConversion("Value is not binary".to_string()))
        }
    }

    /// 尝试将值转换为 NaiveDate 类型
    pub fn as_date(&self) -> Result<NaiveDate> {
        if let Value::Date(d) = self {
            Ok(*d)
        } else {
            Err(VerticaError::TypeConversion("Value is not a date".to_string()))
        }
    }

    /// 尝试将值转换为 NaiveTime 类型
    pub fn as_time(&self) -> Result<NaiveTime> {
        if let Value::Time(t) = self {
            Ok(*t)
        } else {
            Err(VerticaError::TypeConversion("Value is not a time".to_string()))
        }
    }

    /// 尝试将值转换为 NaiveDateTime 类型
    pub fn as_timestamp(&self) -> Result<NaiveDateTime> {
        if let Value::Timestamp(ts) = self {
            Ok(*ts)
        } else {
            Err(VerticaError::TypeConversion("Value is not a timestamp".to_string()))
        }
    }

    /// 尝试将值转换为 Uuid 类型
    pub fn as_uuid(&self) -> Result<Uuid> {
        if let Value::Uuid(u) = self {
            Ok(*u)
        } else {
            Err(VerticaError::TypeConversion("Value is not a uuid".to_string()))
        }
    }

    /// 尝试将值转换为 Decimal 类型
    pub fn as_decimal(&self) -> Result<Decimal> {
        if let Value::Decimal(d) = self {
            Ok(*d)
        } else {
            Err(VerticaError::TypeConversion("Value is not a decimal".to_string()))
        }
    }

    /// 尝试将值转换为 Option<bool> 类型
    pub fn as_option_bool(&self) -> Result<Option<bool>> {
        if let Value::Boolean(b) = self {
            Ok(Some(*b))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<i32> 类型
    pub fn as_option_i32(&self) -> Result<Option<i32>> {
        if let Value::Int(i) = self {
            Ok(Some(*i))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<i64> 类型
    pub fn as_option_i64(&self) -> Result<Option<i64>> {
        if let Value::BigInt(i) = self {
            Ok(Some(*i))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<f32> 类型
    pub fn as_option_f32(&self) -> Result<Option<f32>> {
        if let Value::Float(f) = self {
            Ok(Some(*f))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<f64> 类型
    pub fn as_option_f64(&self) -> Result<Option<f64>> {
        if let Value::Double(f) = self {
            Ok(Some(*f))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<String> 类型
    pub fn as_option_string(&self) -> Result<Option<String>> {
        if let Value::String(s) = self {
            Ok(Some(s.clone()))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<Vec<u8>> 类型
    pub fn as_option_bytes(&self) -> Result<Option<Vec<u8>>> {
        if let Value::Binary(b) = self {
            Ok(Some(b.clone()))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<NaiveDate> 类型
    pub fn as_option_date(&self) -> Result<Option<NaiveDate>> {
        if let Value::Date(d) = self {
            Ok(Some(*d))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<NaiveTime> 类型
    pub fn as_option_time(&self) -> Result<Option<NaiveTime>> {
        if let Value::Time(t) = self {
            Ok(Some(*t))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<NaiveDateTime> 类型
    pub fn as_option_timestamp(&self) -> Result<Option<NaiveDateTime>> {
        if let Value::Timestamp(ts) = self {
            Ok(Some(*ts))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<Uuid> 类型
    pub fn as_option_uuid(&self) -> Result<Option<Uuid>> {
        if let Value::Uuid(u) = self {
            Ok(Some(*u))
        } else {
            Ok(None)
        }
    }

    /// 尝试将值转换为 Option<Decimal> 类型
    pub fn as_option_decimal(&self) -> Result<Option<Decimal>> {
        if let Value::Decimal(d) = self {
            Ok(Some(*d))
        } else {
            Ok(None)
        }
    }

    /// Convert value to string representation
    pub fn to_string_rep(&self) -> String {
        match self {
            Value::Null => "NULL".to_string(),
            Value::Boolean(b) => b.to_string(),
            Value::Int(i) => i.to_string(),
            Value::BigInt(i) => i.to_string(),
            Value::Float(f) => f.to_string(),
            Value::Double(f) => f.to_string(),
            Value::String(s) => s.clone(),
            Value::Binary(b) => format!("{:02x?}", b),
            Value::Date(d) => d.to_string(),
            Value::Time(t) => t.to_string(),
            Value::Timestamp(ts) => ts.to_string(),
            Value::Uuid(u) => u.to_string(),
            Value::Decimal(d) => d.to_string(),
        }
    }

    /// 获取字段类型的描述信息
    pub fn type_description(&self) -> &'static str {
        match self {
            Value::Null => "NULL - 空值类型",
            Value::Boolean(_) => "BOOLEAN - 布尔类型 (true/false)",
            Value::Int(_) => "INTEGER - 32位整数类型",
            Value::BigInt(_) => "BIGINT - 64位整数类型",
            Value::Float(_) => "FLOAT - 32位浮点类型",
            Value::Double(_) => "DOUBLE - 64位浮点类型",
            Value::String(_) => "STRING - 字符串类型 (VARCHAR/CHAR/TEXT)",
            Value::Binary(_) => "BINARY - 二进制数据类型",
            Value::Date(_) => "DATE - 日期类型",
            Value::Time(_) => "TIME - 时间类型",
            Value::Timestamp(_) => "TIMESTAMP - 时间戳类型",
            Value::Uuid(_) => "UUID - 通用唯一标识符类型",
            Value::Decimal(_) => "DECIMAL - 十进制数值类型 (NUMERIC)",
        }
    }

    /// 获取字段类型的简短名称
    pub fn type_name(&self) -> &'static str {
        match self {
            Value::Null => "NULL",
            Value::Boolean(_) => "BOOLEAN",
            Value::Int(_) => "INTEGER",
            Value::BigInt(_) => "BIGINT",
            Value::Float(_) => "FLOAT",
            Value::Double(_) => "DOUBLE",
            Value::String(_) => "STRING",
            Value::Binary(_) => "BINARY",
            Value::Date(_) => "DATE",
            Value::Time(_) => "TIME",
            Value::Timestamp(_) => "TIMESTAMP",
            Value::Uuid(_) => "UUID",
            Value::Decimal(_) => "DECIMAL",
        }
    }

    /// Convert from string
    pub fn from_str(s: &str) -> Self {
        Value::String(s.to_string())
    }

    /// Convert from bytes
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Value::Binary(bytes)
    }

    /// Parse date from string
    pub fn parse_date(s: &str) -> Result<Self> {
        NaiveDate::parse_from_str(s, "%Y-%m-%d")
            .map(Value::Date)
            .map_err(|e| VerticaError::Connection(format!("Invalid date format: {}", e)))
    }

    /// Parse time from string
    pub fn parse_time(s: &str) -> Result<Self> {
        NaiveTime::parse_from_str(s, "%H:%M:%S")
            .map(Value::Time)
            .map_err(|e| VerticaError::Connection(format!("Invalid time format: {}", e)))
    }

    /// Parse timestamp from string
    pub fn parse_timestamp(s: &str) -> Result<Self> {
        NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
            .map(Value::Timestamp)
            .map_err(|e| VerticaError::Connection(format!("Invalid timestamp format: {}", e)))
    }

    /// Parse UUID from string
    pub fn parse_uuid(s: &str) -> Result<Self> {
        Uuid::parse_str(s)
            .map(Value::Uuid)
            .map_err(|e| VerticaError::Connection(format!("Invalid UUID format: {}", e)))
    }

    /// Parse UUID from bytes
    pub fn from_uuid_bytes(bytes: Vec<u8>) -> Result<Self> {
        Uuid::from_slice(&bytes)
            .map(Value::Uuid)
            .map_err(|e| VerticaError::Connection(format!("Invalid UUID bytes: {}", e)))
    }

    /// Convert from i64 timestamp (microseconds since epoch)
    pub fn from_timestamp_micros(micros: i64) -> Result<Self> {
        // 处理Vertica的时间戳格式，使用更安全的范围检查
        const MAX_MICROS: i64 = 253_402_300_799_999_999; // 9999-12-31 23:59:59.999999
        const MIN_MICROS: i64 = -377_705_116_800_000_000; // 1900-01-01 00:00:00.000000
        
        let clamped_micros = micros.clamp(MIN_MICROS, MAX_MICROS);
        
        let seconds = clamped_micros / 1_000_000;
        let nanos = ((clamped_micros % 1_000_000) * 1_000) as u32;
        
        // Vertica 使用 2000-01-01 作为基准
        let epoch = NaiveDate::from_ymd_opt(2000, 1, 1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap();
        
        let duration = Duration::seconds(seconds) + Duration::nanoseconds(nanos as i64);
        let datetime = epoch.checked_add_signed(duration)
            .unwrap_or_else(|| NaiveDate::from_ymd_opt(2000, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap());
        
        Ok(Value::Timestamp(datetime))
    }

    /// Convert from i32 date (Julian date - days since epoch)
    pub fn from_date_days(days: i32) -> Result<Self> {
        // 处理Vertica的日期格式，使用更安全的范围检查
        const MAX_DAYS: i32 = 2_958_465; // 约8100年
        const MIN_DAYS: i32 = -2_451_910; // 约-6700年
        
        let clamped_days = days.clamp(MIN_DAYS, MAX_DAYS);
        
        // Vertica 使用 Julian 日期，从 1900-01-01 开始
        let epoch = NaiveDate::from_ymd_opt(1900, 1, 1)
            .unwrap_or_else(|| NaiveDate::from_ymd_opt(1900, 1, 1).unwrap());
        let date = epoch.checked_add_signed(Duration::days(clamped_days as i64))
            .unwrap_or_else(|| epoch);
        Ok(Value::Date(date))
    }

    /// Convert from i64 time (microseconds since midnight)
    pub fn from_time_micros(micros: i64) -> Result<Self> {
        // 限制时间范围在一天内
        const MAX_MICROS: i64 = 86_400_000_000; // 24小时 = 86400秒 * 1_000_000微秒
        
        if micros < 0 || micros > MAX_MICROS {
            return Err(VerticaError::Connection(format!("Time micros {} out of valid range", micros)));
        }
        
        let secs = micros / 1_000_000;
        let nanos = ((micros % 1_000_000) * 1_000) as u32;
        
        let time = NaiveTime::from_num_seconds_from_midnight_opt(secs as u32, nanos)
            .ok_or_else(|| VerticaError::Connection("Invalid time format".to_string()))?;
        
        Ok(Value::Time(time))
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string_rep())
    }
}

// From implementations for converting Rust types to Value
impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Boolean(b)
    }
}

impl From<i32> for Value {
    fn from(i: i32) -> Self {
        Value::Int(i)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Self {
        Value::BigInt(i)
    }
}

impl From<f32> for Value {
    fn from(f: f32) -> Self {
        Value::Float(f)
    }
}

impl From<f64> for Value {
    fn from(f: f64) -> Self {
        Value::Double(f)
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(s)
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(s.to_string())
    }
}

impl From<Vec<u8>> for Value {
    fn from(bytes: Vec<u8>) -> Self {
        Value::Binary(bytes)
    }
}

impl From<Uuid> for Value {
    fn from(uuid: Uuid) -> Self {
        Value::Uuid(uuid)
    }
}

impl From<NaiveDate> for Value {
    fn from(date: NaiveDate) -> Self {
        Value::Date(date)
    }
}

impl From<NaiveTime> for Value {
    fn from(time: NaiveTime) -> Self {
        Value::Time(time)
    }
}

impl From<NaiveDateTime> for Value {
    fn from(datetime: NaiveDateTime) -> Self {
        Value::Timestamp(datetime)
    }
}

impl From<Decimal> for Value {
    fn from(decimal: Decimal) -> Self {
        Value::Decimal(decimal)
    }
}

// TryFrom implementations for converting Value to Rust types
impl TryFrom<Value> for bool {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Boolean(b) => Ok(b),
            Value::Int(i) => Ok(i != 0),
            Value::BigInt(i) => Ok(i != 0),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to bool", value))),
        }
    }
}

impl TryFrom<Value> for i32 {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Int(i) => Ok(i),
            Value::BigInt(i) => Ok(i as i32),
            Value::Float(f) => Ok(f as i32),
            Value::Double(d) => Ok(d as i32),
            Value::String(s) => s.parse().map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to i32", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to i32", value))),
        }
    }
}

impl TryFrom<Value> for i64 {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Int(i) => Ok(i as i64),
            Value::BigInt(i) => Ok(i),
            Value::Float(f) => Ok(f as i64),
            Value::Double(d) => Ok(d as i64),
            Value::String(s) => s.parse().map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to i64", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to i64", value))),
        }
    }
}

impl TryFrom<Value> for f32 {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Float(f) => Ok(f),
            Value::Double(d) => Ok(d as f32),
            Value::Int(i) => Ok(i as f32),
            Value::BigInt(i) => Ok(i as f32),
            Value::String(s) => s.parse().map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to f32", s))),
            Value::Decimal(d) => Ok(d.to_f32().unwrap_or(0.0)),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to f32", value))),
        }
    }
}

impl TryFrom<Value> for f64 {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Double(d) => Ok(d),
            Value::Float(f) => Ok(f as f64),
            Value::Int(i) => Ok(i as f64),
            Value::BigInt(i) => Ok(i as f64),
            Value::String(s) => s.parse().map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to f64", s))),
            Value::Decimal(d) => Ok(d.to_f64().unwrap_or(0.0)),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to f64", value))),
        }
    }
}

impl TryFrom<Value> for Decimal {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Decimal(d) => Ok(d),
            Value::Int(i) => Ok(Decimal::from(i)),
            Value::BigInt(i) => Ok(Decimal::from(i)),
            Value::Float(f) => Decimal::from_f32(f).ok_or_else(|| VerticaError::TypeConversion(format!("Cannot convert float {} to decimal", f))),
            Value::Double(d) => Decimal::from_f64(d).ok_or_else(|| VerticaError::TypeConversion(format!("Cannot convert double {} to decimal", d))),
            Value::String(s) => s.parse().map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to decimal", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to Decimal", value))),
        }
    }
}

impl TryFrom<Value> for String {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::String(s) => Ok(s),
            Value::Binary(b) => String::from_utf8(b).map_err(|_| VerticaError::TypeConversion("Cannot convert binary to string".to_string())),
            Value::Null => Ok("NULL".to_string()),
            Value::Decimal(d) => Ok(d.to_string()),
            _ => Ok(value.to_string_rep()),
        }
    }
}

impl TryFrom<Value> for Vec<u8> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Binary(b) => Ok(b),
            Value::String(s) => Ok(s.into_bytes()),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to Vec<u8>", value))),
        }
    }
}

impl TryFrom<Value> for NaiveDate {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Date(d) => Ok(d),
            Value::String(s) => NaiveDate::parse_from_str(&s, "%Y-%m-%d")
                .map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to date", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to NaiveDate", value))),
        }
    }
}

impl TryFrom<Value> for NaiveTime {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Time(t) => Ok(t),
            Value::String(s) => NaiveTime::parse_from_str(&s, "%H:%M:%S")
                .map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to time", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to NaiveTime", value))),
        }
    }
}

impl TryFrom<Value> for NaiveDateTime {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Timestamp(ts) => Ok(ts),
            Value::String(s) => NaiveDateTime::parse_from_str(&s, "%Y-%m-%d %H:%M:%S")
                .map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to datetime", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to NaiveDateTime", value))),
        }
    }
}

impl TryFrom<Value> for Uuid {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Uuid(u) => Ok(u),
            Value::String(s) => Uuid::parse_str(&s)
                .map_err(|_| VerticaError::TypeConversion(format!("Cannot convert string '{}' to UUID", s))),
            _ => Err(VerticaError::TypeConversion(format!("Cannot convert {:?} to Uuid", value))),
        }
    }
}

impl TryFrom<Value> for Option<bool> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => bool::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<i32> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => i32::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<i64> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => i64::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<f32> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => f32::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<f64> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => f64::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<String> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => String::try_from(value).map(Some),
        }
    }
}

impl TryFrom<Value> for Option<Decimal> {
    type Error = VerticaError;

    fn try_from(value: Value) -> Result<Self> {
        match value {
            Value::Null => Ok(None),
            _ => Decimal::try_from(value).map(Some),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    #[test]
    fn test_from_impls() {
        let v: Value = 42.into();
        assert_eq!(v, Value::Int(42));

        let v: Value = 3.14.into();
        assert_eq!(v, Value::Double(3.14));

        let v: Value = "hello".into();
        assert_eq!(v, Value::String("hello".to_string()));

        let v: Value = true.into();
        assert_eq!(v, Value::Boolean(true));

        let v: Value = Decimal::from(12345).into();
        assert_eq!(v, Value::Decimal(Decimal::from(12345)));
    }

    #[test]
    fn test_decimal_conversions() {
        let decimal_val = dec!(123.456);
        let value = Value::Decimal(decimal_val);
        
        assert_eq!(value.as_decimal().unwrap(), decimal_val);
        assert_eq!(value.as_option_decimal().unwrap(), Some(decimal_val));
        
        let extracted: Decimal = value.clone().try_into().unwrap();
        assert_eq!(extracted, decimal_val);
        
        let extracted: f64 = value.clone().try_into().unwrap();
        assert_eq!(extracted, 123.456);
    }

    #[test]
    fn test_timestamp_conversion() {
        let ts = NaiveDate::from_ymd_opt(2021, 1, 1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap();
        let v = Value::from(ts);
        assert_eq!(v, Value::Timestamp(ts));
    }

    #[test]
    fn test_value_display() {
        let v = Value::Int(42);
        assert_eq!(format!("{}", v), "42");

        let v = Value::String("hello".to_string());
        assert_eq!(format!("{}", v), "hello");

        let v = Value::Null;
        assert_eq!(format!("{}", v), "NULL");

        let v = Value::Decimal(dec!(123.45));
        assert_eq!(format!("{}", v), "123.45");
    }

    #[test]
    fn test_type_descriptions() {
        let v = Value::Decimal(dec!(99.99));
        assert_eq!(v.type_description(), "DECIMAL - 十进制数值类型 (NUMERIC)");
        assert_eq!(v.type_name(), "DECIMAL");
    }
}

    